package com.xindaoapp.happypet.fragments;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.ChooseAreaDialog;
import com.xindaoapp.happypet.bean.AddressDetailInfo;
import com.xindaoapp.happypet.bean.AddressInfo;
import com.xindaoapp.happypet.bean.AreaInfo;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.KeyValuePair;

/**
 * 编辑收件人和新建收件人
 * 
 * @author chenghao
 * 
 */
@SuppressLint("SdCardPath")
public class NewConsigneeFragment extends BaseFragment {
    private EditText consignee;
    private TextView area;
    private EditText address;
    private EditText phonenumber;
    private EditText code;
    private int[] provincesIDs = new int[3];
    private String addressId = "";
    private List<AreaInfo> list;

    /** 是否可以直接返回 */
    private boolean isCanBack = true;
    boolean isShowTopBar = true;

    private View loading;

    private SQLiteDatabase db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_newconsignee, container, false);
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        list = initSql();
        area = (TextView) view.findViewById(R.id.area);
        consignee = (EditText) view.findViewById(R.id.consignee);
        address = (EditText) view.findViewById(R.id.address);
        phonenumber = (EditText) view.findViewById(R.id.phonenumber);
        code = (EditText) view.findViewById(R.id.code);
        top_bar = view.findViewById(R.id.top_bar);

        Bundle bundle = getArguments();

        if (null != bundle) {

            isShowTopBar = bundle.getBoolean("isShowTopBar", true);

            if (isShowTopBar) {
                top_bar.setVisibility(View.VISIBLE);
            } else {
                top_bar.setVisibility(View.GONE);
            }

            AddressInfo addressDetailInfo =
                    (AddressInfo) bundle.getSerializable(Constants.KEY_CONSIGNEE);
            if (addressDetailInfo != null) {
                addressId = addressDetailInfo.address_id;

                isCanBack = false;

                getMoccaApi().getMyAddressDetail(UserState.getUserUid(),
                        addressDetailInfo.address_id, new IRequest<AddressDetailInfo>() {

                            @Override
                            public void request(AddressDetailInfo t) {
                                if (null != t) {
                                    StringBuffer sb = new StringBuffer();
                                    // 初始化城市地址省市区
                                    for (AreaInfo info : list) {
                                        if (info.id == t.province) {
                                            provincesIDs[0] = info.id;
                                            sb.append(info.name);
                                            for (AreaInfo info2 : info.list) {
                                                if (info2.id == t.city) {
                                                    provincesIDs[1] = info2.id;
                                                    sb.append(info2.name);
                                                    for (AreaInfo info3 : info2.list) {
                                                        if (info3.id == t.district) {
                                                            provincesIDs[2] = info3.id;
                                                            sb.append(info3.name);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    area.setText(sb.toString());
                                    consignee.setText(t.username);
                                    address.setText(t.address);
                                    phonenumber.setText(t.mobile);
                                    code.setText(t.zipcode);
                                    onDataArrived(true);
                                } else {
                                    onDataArrived(true);
                                }
                            }
                        });

            } else {
                // onDataArrived(true);
            }

        }
    }

    @Override
    public boolean handleOptions() {
        // 如果需要处理一些操作，返回true，拦截返回
        if (!isCanBack
                || (!TextUtils.isEmpty(consignee.getText().toString())
                        || !TextUtils.isEmpty(area.getText().toString())
                        || !TextUtils.isEmpty(address.getText().toString())
                        || !TextUtils.isEmpty(phonenumber.getText().toString()) || !TextUtils
                            .isEmpty(code.getText().toString()))) {
            showChooseDialog();
            return true;
        }
        return false;
    }

    private void showChooseDialog() {
        new AlertDialog.Builder(getActivity()).setTitle("确认").setMessage("是否放弃编辑？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isCanBack = true;
                        backFragment();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        // fragment.setVisibility(View.GONE);
        area.setOnClickListener(mOnClickListener);
    }

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.area:
                    ChooseAreaDialog dialog =
                            new ChooseAreaDialog(getActivity(), R.style.Edit_Count_Dialog, list,
                                    new IRequest<KeyValuePair<int[], String[]>>() {

                                        @Override
                                        public void request(KeyValuePair<int[], String[]> t) {
                                            provincesIDs = t.first;
                                            area.setText(t.second[0] + t.second[1] + t.second[2]);
                                        }
                                    });
                    dialog.show();
                    break;

                default:
                    break;
            }
        }
    };
    private View top_bar;

    @Override
    protected void setRightViewListener(View view) {
        super.setRightViewListener(view);
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (checkInput()) {
                    saveConsignee();
                }
            }
        });
    }

    /**
     * 保存联系人
     */
    private void saveConsignee() {
        getMoccaApi().addAddress(UserState.getUserUid(), provincesIDs[0], provincesIDs[1],
                provincesIDs[2], address.getText().toString(), consignee.getText().toString(),
                code.getText().toString(), phonenumber.getText().toString(), "",
                TextUtils.isEmpty(addressId) ? "" : addressId, new IRequest<Boolean>() {

                    @Override
                    public void request(Boolean t) {
                        if (t) {
                            if (TextUtils.isEmpty(addressId)) {
                                Toast.makeText(getActivity(), "保存联系人成功！！！", Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                Toast.makeText(getActivity(), "修改联系人成功！！！", Toast.LENGTH_SHORT)
                                        .show();
                            }
                            // 保存联系人
                            setBundle(new Bundle());
                            backFragment();
                        } else {
                            if (TextUtils.isEmpty(addressId)) {
                                Toast.makeText(getActivity(), "保存联系人失败！！！", Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                Toast.makeText(getActivity(), "修改联系人失败！！！", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }
                    }
                });
    }

    /**
     * 检查输入
     * 
     * @return
     */
    private boolean checkInput() {
        if (TextUtils.isEmpty(consignee.getText().toString())) {
            Toast.makeText(getActivity(), "请输入收货人！！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(area.getText().toString())) {
            Toast.makeText(getActivity(), "请设置所在地区！！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(address.getText().toString())) {
            Toast.makeText(getActivity(), "请输入详细地址！！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(phonenumber.getText().toString())) {
            Toast.makeText(getActivity(), "请输入手机号码！！", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            // 验证手机号是否合法
            if (!isMobileNO(phonenumber.getText().toString())) {
                Toast.makeText(getActivity(), "请输入有效的手机号码！！", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        if (TextUtils.isEmpty(code.getText().toString())) {
            Toast.makeText(getActivity(), "请输入邮政编码！！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    @Override
    protected String getTitleName() {
        return "新建收件人";
    }

    @Override
    protected String getRightName() {
        return "完成";
    }

    /**
     * 流转文件
     * 
     * @param ins
     * @param file
     */
    public static void inputstreamtofile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<AreaInfo> initSql() {
        File file = new File("/data/data/" + getActivity().getPackageName() + "/files/area.db");
        if (!file.exists()) {
            new File("/data/data/" + getActivity().getPackageName() + "/files").mkdir();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            InputStream is = getResources().openRawResource(R.raw.area);
            inputstreamtofile(is, file);
        }
        db =
                SQLiteDatabase.openDatabase(file.getAbsolutePath(), null,
                        SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        // 对数据库进行操作
        List<AreaInfo> provience = getAreaInfos(db, "provience");
        Map<Integer, List<AreaInfo>> city = getAreaInfoMaps(db, "city");
        Map<Integer, List<AreaInfo>> area = getAreaInfoMaps(db, "area");
        // 讲区县添加到市
        for (int i = 0; i < provience.size(); i++) {
            AreaInfo info = provience.get(i);
            info.list = city.get(provience.get(i).id);
            for (int j = 0; j < info.list.size(); j++) {
                info.list.get(j).list = area.get(info.list.get(j).id);
            }
        }
        return provience;
    }

    private List<AreaInfo> getAreaInfos(SQLiteDatabase db, String tableName) {
        List<AreaInfo> list = new ArrayList<AreaInfo>();
        Cursor provience = db.query(tableName, null, null, null, null, null, null);
        if (provience.moveToFirst()) {
            do {
                AreaInfo info = new AreaInfo();
                info.id = provience.getInt(provience.getColumnIndex("id"));
                info.parentid = provience.getInt(provience.getColumnIndex("parentid"));
                info.name = provience.getString(provience.getColumnIndex("name"));
                list.add(info);
            } while (provience.moveToNext());
        }
        return list;
    }

    @SuppressLint("UseSparseArrays")
    private Map<Integer, List<AreaInfo>> getAreaInfoMaps(SQLiteDatabase db, String tableName) {
        Map<Integer, List<AreaInfo>> map = new HashMap<Integer, List<AreaInfo>>();
        Cursor provience = db.query(tableName, null, null, null, null, null, null);
        if (provience.moveToFirst()) {
            do {
                AreaInfo info = new AreaInfo();
                info.id = provience.getInt(provience.getColumnIndex("id"));
                info.parentid = provience.getInt(provience.getColumnIndex("parentid"));
                info.name = provience.getString(provience.getColumnIndex("name"));
                if (map.containsKey(info.parentid)) {
                    map.get(info.parentid).add(info);
                } else {
                    List<AreaInfo> list = new ArrayList<AreaInfo>();
                    list.add(info);
                    map.put(info.parentid, list);
                }
            } while (provience.moveToNext());
        }
        return map;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (db != null) {
            db.close();
        }
    }

}
